import { isVue2, reactive, shallowRef, ComputedRef, computed, getCurrentInstance } from 'vue-demi'

import type { Route } from 'vue-router'
import { useRouter } from './router'

export const useRoute = (): Route => {
  if (!isVue2) {
    return new Error('该hook只能在vue2环境使用') as any as Route
  }
  const router = useRouter()

  /**
   * 获取路由实例
   */
  // @ts-ignore
  const route = getCurrentInstance()?.proxy?.$route as Route

  const routeRef = shallowRef(
    route ||
      ({
        path: '/',
        name: undefined,
        params: {},
        query: {},
        hash: '',
        fullPath: '/',
        matched: [],
        meta: {},
        redirectedFrom: undefined,
      } as Route)
  )

  const computedRoute = {} as {
    [key in keyof Route]: ComputedRef<Route[key]>
  }

  for (const key of Object.keys(routeRef.value) as (keyof Route)[]) {
    computedRoute[key] = computed<any>(() => routeRef.value[key])
  }

  router.afterEach((to) => (routeRef.value = to))

  return reactive(computedRoute)
}
